package com.github.ghsea.framework.job.common;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.data.Stat;

import com.github.ghsea.framework.zkclient.ChildrenChangedListener;

public class EndpointChangedListener extends ChildrenChangedListener {

	private CopyOnWriteArrayList<Endpoint> allEndpoints;

	private Object lock = new Object();

	public List<Endpoint> all() {
		return allEndpoints;
	}

	public EndpointChangedListener() {
		allEndpoints = new CopyOnWriteArrayList<Endpoint>();
	}

	public void init(List<Endpoint> serverNodes) {
		Objects.nonNull(serverNodes);

		synchronized (lock) {
			serverNodes.forEach(e -> {
				allEndpoints.add(e);
			});
		}
	}

	@Override
	public void notifyChildAdded(String childAdded, Object data) {
		EndpointZkNodeData zkNodeData = (EndpointZkNodeData) data;
		Endpoint serverAdded = Endpoint.build(ZKPaths.getNodeFromPath(childAdded), zkNodeData.getBaseAccessUrl());
		synchronized (lock) {
			if (!allEndpoints.contains(serverAdded)) {
				allEndpoints.add(serverAdded);
			}
		}
	}

	@Override
	public void notifyChildRemoved(String childRemoved) {
		allEndpoints.remove(Endpoint.build(ZKPaths.getNodeFromPath(childRemoved), null));
	}

	@Override
	public void notifyChildUpdated(String childUpdated, Stat stat, Object data) {
		// TODO Auto-generated method stub

		// do nothing currently

	}

}
